package com.shey.qiuckpictest;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;

import com.shey.adapter.SubGroupAdapter;
import com.shey.base.BaseActivity;
import com.shey.bean.GroupPhoto;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";
    private static long mLastBackTime = 0;
    private GridView mGridView;
    private SubGroupAdapter mSubGroupAdapter = null;
    private DrawerLayout mDrawerLayout;
    private ScanPhotoTask mScanPhotoTask = null;
    private ListView mDrawerList;
    private String[] mDrawerListTitles;

    private HashMap<String, ArrayList<String>> mAllGroupMap;

    private AdapterView.OnItemClickListener mGridViewOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            GroupPhoto mGroupPhoto = (GroupPhoto) mSubGroupAdapter.getItem(position);
            if (mGroupPhoto == null)
                return;

            Bundle bundle = new Bundle();
            bundle.putString(ChildPhotoActivity.GROUP_NAME, mGroupPhoto.getGroupName());
            bundle.putStringArrayList(ChildPhotoActivity.CHILD_PHOTO_LIST, mAllGroupMap.get(mGroupPhoto.getAbsolutePath()));
            forward(ChildPhotoActivity.class, bundle, false);
        }
    };

    private AdapterView.OnItemClickListener mDrawerListItemListner = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mDrawerLayout != null) {
                if (position != 0) {
                    if (mDrawerListTitles != null) {
                        toast(mDrawerListTitles[position] + " 待开发");
                    }
                }
                mDrawerLayout.closeDrawer(Gravity.LEFT);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState, View decorView) {

        enabledHomeButton();

        mSubGroupAdapter = new SubGroupAdapter(mContext, null);
        mGridView.setAdapter(mSubGroupAdapter);
        mGridView.setOnItemClickListener(mGridViewOnItemClickListener);

        mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerListTitles));
        mDrawerList.setOnItemClickListener(mDrawerListItemListner);

        mScanPhotoTask = new ScanPhotoTask();
        mScanPhotoTask.execute();
    }

    /**
     * 扫描系统图片的异步任务
     */
    private class ScanPhotoTask extends AsyncTask<Void, Integer, List<GroupPhoto>> {

        @Override
        protected void onPreExecute() {
            mAllGroupMap = new HashMap<>();
        }

        @Override
        protected List<GroupPhoto> doInBackground(Void... params) {
            Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            ContentResolver mContentResolver = getContentResolver();

            //只查询jpg与png的图片
            Cursor mCursor = mContentResolver.query(mImageUri, null,
                    MediaStore.Images.Media.MIME_TYPE + "=? or "
                            + MediaStore.Images.Media.MIME_TYPE + "=?",
                    new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);

            if (mCursor == null) {
                return null;
            }

            while (mCursor.moveToNext()) {
                //获取图片路径
                String imagePath = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                //获取图片路径父级文件名
                String parentAbsolutePath = new File(imagePath).getParentFile().getAbsolutePath();

                if (!mAllGroupMap.containsKey(parentAbsolutePath)) {
                    ArrayList<String> childList = new ArrayList<>();
                    childList.add(imagePath);
                    mAllGroupMap.put(parentAbsolutePath, childList);
                    Log.e(TAG, "绝对路径：" + parentAbsolutePath);
                } else {
                    mAllGroupMap.get(parentAbsolutePath).add(imagePath);
                }
            }
            //关闭游标
            mCursor.close();

            return groupOfPhoto();
        }

        /**
         * 耗时任务处理完后，主线程的处理
         *
         * @param groupPhotos
         */
        @Override
        protected void onPostExecute(List<GroupPhoto> groupPhotos) {
            //如果为空就不进行适配器重新绑定
            if (groupPhotos == null || groupPhotos.size() <= 0)
                return;

            mSubGroupAdapter.removeAll();
            mSubGroupAdapter.addAll(groupPhotos);
        }
    }

    /**
     * 对图片进行组别处理,以让适配器绑定数据
     *
     * @return
     */
    private List<GroupPhoto> groupOfPhoto() {

        List<GroupPhoto> mGroupPhotoList = new ArrayList<>(mAllGroupMap.size() > 0 ? mAllGroupMap.size() : 0);
        Iterator<Map.Entry<String, ArrayList<String>>> iterator = mAllGroupMap.entrySet().iterator();

        GroupPhoto mGroupPhoto;
        while (iterator.hasNext()) {
            Map.Entry<String, ArrayList<String>> entry = iterator.next();
            String parentAbsoulutePath = entry.getKey();
            List<String> childList = entry.getValue();

            mGroupPhoto = new GroupPhoto();
            mGroupPhoto.setGroupName(new File(parentAbsoulutePath).getName());
            mGroupPhoto.setAbsolutePath(parentAbsoulutePath);
            mGroupPhoto.setPath(childList.get(0));
            mGroupPhoto.setPhotoSize(childList.size());
            mGroupPhotoList.add(mGroupPhoto);

            Log.e("组名:", new File(parentAbsoulutePath).getName());
            Log.e("路径：", childList.get(0));
        }

        return mGroupPhotoList;
    }

    /**
     * 启用HomeButton
     */
    private void enabledHomeButton() {
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.app_name, R.string.app_name);
        actionBarDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void findView() {
        mDrawerListTitles = getResources().getStringArray(R.array.draw_list_array);
        mToolBar.setTitle(R.string.app_name);
        mToolBar.setTitleTextColor(getApplicationContext().getResources().getColor(R.color.white));
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer);
        mDrawerList = (ListView) findViewById(R.id.lv_left_drawer);
        mGridView = (GridView) findViewById(R.id.main_gridview);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerLayout.closeDrawers();
                return true;
            }

            if (System.currentTimeMillis() - mLastBackTime > 2000) {
                toast(getString(R.string.press_will_exit));
                mLastBackTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }
        if (id == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerLayout.closeDrawers();
            } else {
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        if (mScanPhotoTask != null) {
            mScanPhotoTask.cancel(true);
            mScanPhotoTask = null;
        }

        mGridViewOnItemClickListener = mGridView.getOnItemClickListener();
        mGridViewOnItemClickListener = null;

        if (mAllGroupMap != null && mAllGroupMap.size() > 0) {
            mAllGroupMap.clear();
            mAllGroupMap = null;
        }
        super.onDestroy();
    }
}
